import React from 'react';
import LineChart from './lineChart';
import { Chart, Tooltip, Legend, Point, Line, Interval } from 'bizcharts';

type PropField = {
  datas: Record<string, any>[];
  xCol: string;
  yCol: string;
  zCol: string;
  height: number;
};
const LineColumnChart: React.FC<PropField> = (props) => {
  const { datas, xCol, yCol, zCol, height } = props;
  let chartIns: { geometries: any } | null = null;
  if (!datas) {
    return <div />;
  }
  let minVal = 6000000;
  let hasAvvl = true;
  for (let i = 0; i < datas.length; i++) {
    if (datas[i][zCol] && datas[i][zCol] < minVal) {
      minVal = datas[i][zCol];
    }
    if (datas[i][yCol] !== undefined) {
      if (datas[i][yCol] < minVal) {
        minVal = datas[i][yCol];
      }
    } else {
      hasAvvl = false;
    }
  }
  if (!hasAvvl) {
    return <LineChart datas={datas} xCol={xCol} yCol={zCol} height={height} />;
  }
  if (minVal > 0) {
    minVal = minVal - minVal * 0.01;
  }
  const scale = {
    [yCol]: {
      min: minVal,
      tickCount: 4,
      alias: '日均',
      type: 'linear-strict',
    },
    [zCol]: {
      min: minVal,
      tickCount: 4,
      alias: '时点',
      type: 'linear-strict',
    },
  };
  const colors = ['#6394f9', '#62daaa'];
  return (
    <Chart
      scale={scale}
      autoFit
      height={height}
      data={datas}
      onGetG2Instance={(chart: { geometries: any } | null) => {
        chartIns = chart;
      }}
    >
      <Legend
        custom={true}
        allowAllCanceled={true}
        items={[
          {
            value: { yCol },
            name: '日均',
            marker: {
              symbol: 'square',
              style: { fill: colors[0], r: 5 },
            },
          },
          {
            value: { zCol },
            name: '时点',
            marker: {
              symbol: 'hyphen',
              style: { stroke: colors[1], r: 5, lineWidth: 3 },
            },
          },
        ]}
        onChange={(ev) => {
          const item = ev!.item;
          const key = Object.keys(item.value)[0];
          const value = item.value[key];
          const checked = !item.unchecked;
          const geoms = chartIns!.geometries;
          for (let i = 0; i < geoms.length; i++) {
            const geom = geoms[i];
            const ys = geom.getYScale();
            if (ys.field === value) {
              if (checked) {
                geom.show();
              } else {
                geom.hide();
              }
            }
          }
        }}
      />
      <Tooltip shared />
      <Interval position={`${xCol}*${yCol}`} color={colors[0]} />
      <Line position={`${xCol}*${zCol}`} color={colors[1]} size={3} shape="smooth" />
      <Point position={`${xCol}*${zCol}`} color={colors[1]} size={3} shape="circle" />
    </Chart>
  );
};
export default LineColumnChart;
